<?php

namespace app\home\controller;

// 引入公共控制器
use app\common\controller\Home;

class Index extends Home
{

    //不需要登录属性
    protected $NoNeedLogin = ['*'];
    // 定义用户模型属性
    protected $BusinessModel = null;

    // 定义课程模型
    protected $SubjectModel = null;
    //定义老师模型
    protected $TeacherModel = null;

    //课程分类模型
    protected $CategoryModel = null;

    //课程章节模型
    protected $ChapterModel = null;

    //评论模型
    protected $CommentModel = null;

    //点赞模型
    protected $LikeModel = null;

    //订单模型
    protected $OrderModel = null;

    // 构造函数
    public function __construct()
    {
        // 手动继承父级的构造函数
        parent::__construct();

        // 加载模型
        $this->BusinessModel = model('business.Business');
        $this->SubjectModel = model('subject.Subject');
        $this->TeacherModel = model('subject.Teacher');
        $this->CategoryModel = model('subject.Category');
        $this->ChapterModel = model('subject.Chapter');
        $this->CommentModel = model('subject.Common');
        $this->LikeModel = model('subject.Like');
        $this->OrderModel = model('subject.Order');
    }


    public function index()
    {
        // 轮播图数据
        $topList = $this->SubjectModel->group('cateid')->order('id desc')->limit(6)->select();

        // halt(collection($topList)->toArray());

        // 课程数据
        $subjectList = $this->SubjectModel->order('id desc')->limit(10)->select();
        // halt($subjectList);

        // 讲师数据
        $teacherList = $this->TeacherModel->limit(10)->select();
        // halt($teacherList);

        // 模板赋值
        $this->assign([
            'topList' => $topList,
            'subjectList' => $subjectList,
            'teacherList' => $teacherList
        ]);


        //输出相应的视图
        return $this->fetch();
    }


    public function register()
    {
        $token = $this->request->param('token', '', 'trim');

        if (!empty($token)) {
            $businessList = $this->BusinessModel->field('id,mobile')->select();

            foreach ($businessList as $item) {
                // 模拟token加密
                $val = md5($item['id'] . $item['mobile']);

                if ($val == $token) {
                    cookie('token', $val);
                    break;
                }
            }
        }

        if ($this->request->isPost()) {

            // 助手函数 halt => 调试并且中断后面代码执行
            // halt($this->request->post('mobile'));

            $mobile = $this->request->param('mobile', '', 'trim');
            $password = $this->request->param('password', '', 'trim');
            $token = $this->request->param('token', '', 'trim');

            if (empty($password)) {
                // 操作失败时所提示信息
                $this->error('密码不能为空');
            }

            // 生成密码盐
            $salt = build_randstr();

            // 拼接并且加密
            $password = md5($password . $salt);

            // 查询数据表
            $sourceid = model('business.Source')->where(['name' => ['LIKE', '%云课堂%']])->value('id');

            // 调试执行的SQL语句
            // halt(Db::getLastSql());

            // 返回当前的查询SQL而不执行
            // halt(Db::name('business_source')->where(['name' => ['LIKE','%云课堂%']])->fetchSql()->value('id'));

            //封装数据
            $data = [
                'mobile' => $mobile,
                'nickname' => build_encrypt($mobile, 3, 4),
                'salt' => $salt,
                'password' => $password,
                'sourceid' => $sourceid
            ];

            // 判断是否有推荐人
            $token = empty($token) ? cookie('token') : $token;

            if (!empty($token)) {
                $businessList = $this->BusinessModel->field('id,mobile')->select();

                foreach ($businessList as $item) {
                    $val = md5($item['id'] . $item['mobile']);

                    if ($val == $token) {
                        $data['parentid'] = $item['id'];
                        break;
                    }
                }
            }

            $result = $this->BusinessModel->validate('common/business/Business')->save($data);

            if ($result === false) {
                // 获取模型错误信息
                $this->error($this->BusinessModel->getError());
            } else {
                $this->success('注册成功', url('/home/index/login'));
            }
        }

        return $this->fetch();
    }



    public function login()
    {
        if ($this->request->isPost()) {
            // 接收参数
            $mobile = $this->request->param('mobile', '', 'trim');
            $password = $this->request->param('password', '', 'trim');

            // 查询数据表是否有该用户
            $business = $this->BusinessModel->where(['mobile' => $mobile])->find();

            if (empty($business)) {
                $this->error('该手机未注册');
            }

            // 验证密码是否正确
            $password = md5($password . $business['salt']);

            if ($password != $business['password']) {
                $this->error('密码错误');
            }

            $data = [
                'id' => $business['id'],
                'mobile' => $business['mobile']
            ];

            // 存储用户登录信息
            cookie('business', $data);

            // 获取是否有返回上一个界面
            $redirect = cookie('redirect');

            if ($redirect) {
                $this->success('登录成功', $redirect);
            } else {
                $this->success('登录成功', url('/home/business/index'));
            }
        }

        return $this->fetch();
    }


    //退出登录
    public function logout()
    {
        // 判断是否是ajax请求
        if ($this->request->isAjax()) {
            cookie('business', null);

            $this->success('退出成功', url('/home/index/login'));
        }
    }

    //底部导航栏的搜索模块
    public function search()
    {

        if ($this->request->isPost()) {

            //接收参数
            $params = $this->request->param();

            $search = trim($params['search']);

            $subjectList = $this->SubjectModel->order('id desc')->select();

            $business = $this->BusinessModel->order('id desc')->limit(10)->select();

            // halt(collection($subjectList)->toArray());

            $business = collection($business)->toArray();
            // halt($business);

            // foreach ($business as $item) {
            //     echo $item['id'];
            //     echo "</br>";
            // }
            // exit;

            $this->assign([
                'search' => $search,
                'subjectList' => $subjectList,
                'business' => $business
            ]);
        }
        return $this->fetch();
    }

    //课程详情
    public function collect()
    {
        //接收课程id
        $subid = $this->request->param('subject', '' . 'trim');
        cookie('subid', $subid);
        $num = $this->request->param('num', 0, 'trim');

        //首先拿登录用户id
        $business = $this->IsLogin(false);

        //查询课程表
        $subject = $this->SubjectModel->where(['id' => $subid])->find();
        $subjects = $this->SubjectModel->where(['id' => $subid])->select();

        $btnlike = [
            'busid' => $business['id'],
            'subid' => $subid,
            'like' => $num
        ];
        $bnLike = $this->LikeModel->where(['busid' => $business['id'], 'subid' => $subid])->find();

        if (!$bnLike) {
            $bnLike = $this->LikeModel->save($btnlike);
        }
        if (!$subject) {
            $this->error('课程不存在');
        }

        $subject['like_status'] = false;

        if ($business) {
            $busid = $business['id'] ?? 0;

            $where = [
                'busid' => $busid,
            ];
        }

        $subfenlei = [];
        $teacherid = [];

        foreach ($subjects as $value) {
            $subfenlei[] = $value['cateid'];
            $teacherid[] = $value['teacherid'];
        };

        //查询课程分类
        $category = $this->CategoryModel->where(['id' => ['IN', $subfenlei]])->find();

        //查询老师
        $teacher = $this->TeacherModel->where(['id' => ['IN', $teacherid]])->find();

        //查询课程章节
        $chapter = $this->ChapterModel->where(['subid' => $subid])->select();

        //查询订单是否存在
        $order = $this->OrderModel->validate('common/subject/Order')->where(['subid' => $subid, 'busid' => $business['id']])->find();

        $this->assign([
            'subject' => $subject,
            'category' => $category,
            'teacher' => $teacher,
            'chapter' => $chapter,
            'bnLikes' => $bnLike,
            'order' => $order
        ]);

        return $this->fetch();
    }


    //课程评论区
    public function comment()
    {
        if ($this->request->isAjax()) {
            $subid = $this->request->param('subid', '', 'trim');
            $page = $this->request->param('page', 1, 'trim');
            $limit = $this->request->param('limit', 10, 'trim');

            $Subject = $this->SubjectModel->where(['id' => $subid])->find();

            if (!$Subject) {
                $this->error("课程不存在");
            }

            //查询评论
            $comment = $this->CommentModel->with('business')->where(['subid' => $subid])->page($page, $limit)->select();

            //查询评论个数
            $count = $this->CommentModel->with('business')->where(['subid' => $subid])->count();

            $data = [
                'common' => $comment,
                'count' => $count
            ];

            if ($comment) {
                $this->success("评论存在", null, $data);
            } else {
                $this->error("评论不存在", null, $data);
            }
        }
        $this->fetch();
    }

    //课程点赞
    public function btndz()
    {
        if ($this->request->isAjax()) {

            //接收课程id
            $subid = $this->request->param('subid', '', 'trim');
            $num = $this->request->param('numtext', '', 'trim');

            $business = $this->IsLogin(false);  //获取用户id

            //查询课程是否存在
            $like = $this->SubjectModel->where(['id' => $subid])->find();

            if (!$like) {
                $this->error("课程不存在");
            }

            $nums = 0;
            if ($num == 0) {
                $likes = $like['likes'] + 1;
                $nums = 1;
            } else {
                $likes = $like['likes'] - 1;
                $nums = 0;
            }

            $btnlike = [
                'busid' => $business['id'],
                'subid' => $subid,
                'like' => $nums
            ];

            $btnlikess = $this->LikeModel->where(['busid' => $business['id'], 'subid' => $subid])->find();

            if (!$btnlikess) {
                $upSubLike = $this->LikeModel->save($btnlike);
            } else {
                $upLike = $this->LikeModel->where(['busid' => $business['id'], 'subid' => $subid])->update(['like' => $nums]);  //更新用户课程点赞表         
                if (!$upLike) {
                    $this->error("个人课程点赞更新失败");
                }
            }

            $bnLike = $this->LikeModel->where(['busid' => $business['id'], 'subid' => $subid])->find();

            $where = [
                'likes' => $likes
            ];
            // halt($where);

            //更新课程点赞数
            $updatelikes = $this->SubjectModel->where(['id' => $subid])->update($where);

            if (!$updatelikes) {
                $this->error("更新失败");
            }

            $like_count = $this->SubjectModel->where(['id' => $subid])->find();

            $data = [
                'like_count' => $like_count,
                'like' => $like,
                'subLike' => $bnLike
            ];

            if ($like) {
                $this->success("点赞成功", null, $data);
            } else {
                $this->error("取消点赞", null, $data);
            }
        }

        return $this->fetch();
    }

    //课程购买
    public function buy()
    {
        if ($this->request->isAjax()) {

            $buyed = $this->request->param('buy', '', 'trim');
            $subid = $this->request->param('subid', '', 'trim');

            $business = $this->IsLogin(false);  //获取用户id

            if ($buyed == '购买') {
                $buy = 1;
            }

            $data = [
                'busid' => $business['id'],
                'subid' => $subid,
                'buy' => 0
            ];

            $shop = $this->LikeModel->where($data)->find();

            if ($shop) {

                $shop = $this->LikeModel->where(['busid' => $business['id'], 'subid' => $subid])->update(['buy' => $buy]);

                if ($shop) {
                    $shop = $this->LikeModel->where(['busid' => $business['id'], 'subid' => $subid])->find();
                    $this->success("购买成功", null, $shop);
                } else {
                    $this->error("已购买", null, $shop);
                }
            } else {
                $shop = $this->LikeModel->where(['busid' => $business['id'], 'subid' => $subid])->find();
                $this->error("已购买", null, $shop);
            }
        }
        $this->fetch();
    }

    //章节点击
    public function play()
    {
        if ($this->request->isAjax()) {
            $subid = $this->request->param('subid', '', 'trim');
            $cid = $this->request->param('cid', 0, 'trim');
            $busid = $this->IsLogin(false);

            $subject = $this->SubjectModel->find(['id' => $subid]);
            if (!$subject) {
                $this->error('课程不存在');
            }

            $buy = [
                'subid' => $subid,
                'busid' => $busid['id'],
            ];

            //用户是否有购买该课程
            $buyed = $this->OrderModel->where($buy)->find();

            if (!$buyed) {
                $this->error("未购买该课程");
            }

            //查询课程章节
            $chapter = $this->ChapterModel->where(['subid' => $subid])->find();

            if ($chapter) {
                $this->success("播放成功", null, ['url' => $chapter['url']]);
            } else {
                $this->error("章节不存在");
            }
        }
        $this->fetch();
    }


    //课程收藏
    public function save()
    {
        if ($this->request->isAjax()) {
            $collect = $this->request->param('collect', '', 'trim');
            $subid = $_COOKIE['subid'];
            $busid = $this->IsLogin(false);
            $data = ['busid' => $busid['id'],'subid' => $subid];
      
            $upcollect = $this->LikeModel->where($data)->find();
       
            if (!$upcollect) {
                $this->error("数据不存在");
            }

            $upcollect = $this->LikeModel->where($data)->update(['collect' => $collect]);
            if (!$upcollect) { 
                $this->error("更新失败");
            }
          
            $collect = $this->LikeModel->where($data)->find();
            if ($upcollect) {
                $this->success("收藏成功",null,$collect);
            }else{
                $this->error("取消收藏",null,$collect);
            }

        }
    }
}
